package com.extractgmailaddress.action
{
    import com.extractgmailaddress.helper.MainHelper;
    import com.extractgmailaddress.logic.MainLogic;
    import com.extractgmailaddress.view.MainView;
    import com.extractgmailaddress.vo.User;
    
    import flash.desktop.NativeApplication;
    import flash.display.NativeMenu;
    import flash.display.NativeMenuItem;
    import flash.display.NativeWindow;
    import flash.events.Event;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.net.FileFilter;
    
    import mx.collections.ArrayCollection;
    import mx.core.Application;
    
    import org.seasar.akabana.yui.framework.event.FrameworkEvent;

    public class MainAction
    {
        public var helper:MainHelper;
        public var logic:MainLogic;
        public var view:MainView;

        private const INDEX_OF_FIST_NAME:int = 0;
        private const INDEX_OF_EMAIL_ADDRESS:int = 28;
        private const INDEX_OF_PHONE_NUMBER:int = 34;

        private var openDir:File = File.documentsDirectory;
        private var openFile:File;

        /**
         * アプリケーション起動時の初期化処理です。
         * @param event FrameworkEvent
         */
        public function onApplicationStartHandler(event:FrameworkEvent):void
        {
            // メニューの初期化
            initMenu();
            // ウィンドウの初期化
            initWindow();
        }
        
        /**
         * アプリケーションを最大化します。
         */
        private function initWindow():void
        {
            helper.windowMaximize();
        }
        
        /**
         * メニューの初期化を行います。
         */
        private function initMenu():void
        {
            var rootMenu:NativeMenu = new NativeMenu();
            
            const separator:NativeMenuItem = new NativeMenuItem("", true);
            
            var fileMenu:NativeMenuItem = rootMenu.addSubmenu(new NativeMenu(), "ファイル");
            
            var readFileMenuItem:NativeMenuItem = new NativeMenuItem("ファイルを読み込み");
            readFileMenuItem.addEventListener(Event.SELECT, readFileButtonClickHandler);
            fileMenu.submenu.addItem(readFileMenuItem);
            fileMenu.submenu.addItem(separator);
            
            var exitMenuItem:NativeMenuItem = new NativeMenuItem("終了");
            exitMenuItem.addEventListener(Event.SELECT, helper.exit);
            fileMenu.submenu.addItem(exitMenuItem);
            
            var editMenu:NativeMenuItem = rootMenu.addSubmenu(new NativeMenu(), "編集");
            
            var outputAddressMenuItem:NativeMenuItem = new NativeMenuItem("アドレス取り出し");
            outputAddressMenuItem.addEventListener(Event.SELECT, outputAddressButtonClickHandler);
            editMenu.submenu.addItem(outputAddressMenuItem);
            
            var listMenu:NativeMenuItem = rootMenu.addSubmenu(new NativeMenu(), "リスト");
            
            var checkAllMenuItem:NativeMenuItem = new NativeMenuItem("すべてチェック");
            checkAllMenuItem.addEventListener(Event.SELECT, checkAllButtonClickHandler);
			listMenu.submenu.addItem(checkAllMenuItem);
			
			var unCheckAllMenuItem:NativeMenuItem = new NativeMenuItem("すべてチェック解除");
            unCheckAllMenuItem.addEventListener(Event.SELECT, unCheckAllButtonClickHandler);
			listMenu.submenu.addItem(unCheckAllMenuItem);
            
            if (NativeApplication.supportsMenu)
            {
                NativeApplication.nativeApplication.menu = rootMenu;
            }
            else if (NativeWindow.supportsMenu)
            {
                Application.application.stage.nativeWindow.menu = rootMenu;
            }
        }

        public function readFileButtonClickHandler(event:Event):void
        {
            var fileToOpen:File = new File();
            var txtFilter:FileFilter = new FileFilter("Gmailアドレス連絡先データ(CSV)", "*.csv");

            openDir.addEventListener(Event.SELECT, onSelectOpenFile);
            openDir.browseForOpen("csvファイル", [txtFilter]);
        }

        public function outputAddressButtonClickHandler(event:Event):void
        {
            var addressData:ArrayCollection = ArrayCollection(helper.sendMailTextAreaText);
            
            if (!addressData)
            {
            	return;
            }
            
            var addressDataLength:int = addressData.length;
            var addressArray:Array = new Array();
            for (var i:int = 0; i < addressDataLength; i++)
            {
                var user:User = User(addressData.getItemAt(i));
                if (user.check)
                {
                    addressArray.push(user.address);
                }
            }
            
            helper.showSendAddress(addressArray.join(","));
        }

        private function onSelectOpenFile(e:Event):void
        {
            // 選択されたファイル
            openFile = e.target as File;
            openDir.removeEventListener(Event.SELECT, onSelectOpenFile);
            var fileStream:FileStream = new FileStream();
            fileStream.open(openFile, FileMode.READ);
            var fileData:String = fileStream.readMultiByte(fileStream.bytesAvailable, "utf-16");

            var listData:ArrayCollection = new ArrayCollection();
            var lines:Array = fileData.split("\n");
            var linesLength:int = lines.length;
            for (var i:int = 1; i < linesLength; i++)
            {
                var splitAddress:Array = String(lines[i]).split(",");
                var user:User = new User();
                user.name = splitAddress[INDEX_OF_FIST_NAME];
                user.address = splitAddress[INDEX_OF_EMAIL_ADDRESS];
                user.phoneNumber = splitAddress[INDEX_OF_PHONE_NUMBER];
                user.check = true;
                listData.addItem(user);
            }

            helper.showUserData(listData);
        }

        public function checkAllButtonClickHandler(event:Event):void
        {
            helper.checkAllUserData();
        }

        public function unCheckAllButtonClickHandler(event:Event):void
        {
            helper.unCheckAllUserData();
        }
    }
}